using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFS.Kanban.Domain;
using TFS.Kanban.VS2010.Queries;
using TFS.Kanban.VS2010.Queries.Extensions;
namespace TFS.Kanban.VS2010.Services
{
    internal class WorkItemService : IWorkItemService
    {
        const string _activeQuery = "Select * from Issue where (State = 'Active') order by Title";
        const string _nonClosedQuery = "Select * from Issue where (State <> 'Closed') order by Title";
        const string _allQuery = "Select * from Issue order by Title";

        private const string _workItemQuery = "Select * from Issue where (Id = '{0}')";

        private readonly IProjectCollectionService _projectCollectionService;
        private readonly WorkItemStore _workItemStore;

        public WorkItemService(IProjectCollectionService projectCollectionService)
        {
            _projectCollectionService = projectCollectionService;

            var projectCollection = _projectCollectionService.GetProjectCollection();
            _workItemStore = projectCollection.GetService<WorkItemStore>();
        }

        public WorkItem GetWorkItem(int id)
        {
            var workItems = _workItemStore.Query(string.Format(_workItemQuery, id));
            return workItems.Cast<WorkItem>().FirstOrDefault();
        }

        public IEnumerable<WorkItem> GetWorkItems(string path, string type)
        {
            return _workItemStore.QueryWorkItems()
                                 .Where(x => x.IterationPath, WIQLOperator.Under, path)
                                 .And(x => x.Type, WIQLOperator.Equal, type)
                                 .Execute();
        }

        public IEnumerable<WorkItem> GetWorkItems(IProject project)
        {
            var parameters = new Dictionary<string, object>();
            parameters.Add("Project", project.Name);
            var workItems = _workItemStore.Query(_allQuery, parameters);
            return workItems.Cast<WorkItem>().Where(workItem => workItem.Project.Id == project.Id);
        }
    }

    internal static class WIQLQuery
    {
        
    }
}